package com.xj.demo;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class ProdManagerHttpServer {
    // 定义时间格式器（线程安全）
    private static final DateTimeFormatter TIME_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    // 默认端口号
    private static final int DEFAULT_PORT = 90;

    public static void main(String[] args) throws IOException {
        // 解析端口参数（如果未传入参数，则使用默认值90）
        int port = args.length > 0 ? Integer.parseInt(args[0]) : DEFAULT_PORT;

        // 创建HTTP服务器，绑定到指定端口
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);

        // 设置"/hello"路径的处理程序
        server.createContext("/hello", new HelloHandler());

        // 启动服务器
        server.start();
        System.out.println("Server started on port " + port + ". Press ENTER to exit.");

        // 保持服务器运行
        // System.in.read();
        // server.stop(0);
    }

    static class HelloHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            try {
                // 验证请求方法
                if (!"GET".equalsIgnoreCase(exchange.getRequestMethod())) {
                    exchange.sendResponseHeaders(405, -1);
                    exchange.close();
                    return;
                }

                // 解析请求参数
                Map<String, String> params = parseQueryParams(exchange.getRequestURI().getQuery());

                // 生成带完整时间戳的响应
                String timestamp = LocalDateTime.now().format(TIME_FORMATTER);
                String response = "access success " + timestamp;

                // 如果传入参数 val=1，执行 Shell 脚本
                if ("1".equals(params.get("val"))) {
                    executeShellScript("/opt/start_xj_slave.sh");
                    response += "\nShell script executed: start_xj_slave.sh";
                }

                // 配置响应参数
                exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
                byte[] responseData = response.getBytes("UTF-8");

                // 发送响应
                exchange.sendResponseHeaders(200, responseData.length);
                try (OutputStream os = exchange.getResponseBody()) {
                    os.write(responseData);
                }
            } catch (Exception e) {
                e.printStackTrace();
                exchange.sendResponseHeaders(500, -1); // 返回 500 错误
            } finally {
                exchange.close();
            }
        }

        /**
         * 解析查询参数
         * @param query 查询字符串（如 "val=1&name=test"）
         * @return 参数键值对
         */
        private Map<String, String> parseQueryParams(String query) {
            Map<String, String> params = new HashMap<>();
            if (query != null) {
                for (String param : query.split("&")) {
                    String[] pair = param.split("=");
                    if (pair.length == 2) {
                        params.put(pair[0], pair[1]);
                    }
                }
            }
            return params;
        }

        /**
         * 执行本地 Shell 脚本
         * @param scriptPath 脚本路径
         * @throws IOException 如果执行失败
         */
        private void executeShellScript(String scriptPath) throws IOException {
            ProcessBuilder processBuilder = new ProcessBuilder(scriptPath);
            processBuilder.redirectErrorStream(true); // 合并标准错误和标准输出
            Process process = processBuilder.start();

            // 读取脚本输出
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println("[Shell Output] " + line);
                }
            }

            // 等待脚本执行完成
            try {
                int exitCode = process.waitFor();
                System.out.println("Shell script exited with code: " + exitCode);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new IOException("Shell script execution interrupted", e);
            }
        }
    }
}